package com.samphanie.auiu.library.restful

import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.util.concurrent.ConcurrentHashMap

/**
 * @author Dries
 **/
open class AuiuRestful constructor(
    val baseUrl: String,
    val callFactory: AuiuCall.Factory
) {

    private var interceptors: MutableList<AuiuInterceptor> = mutableListOf()
    private var methodService: ConcurrentHashMap<Method, MethodParser> = ConcurrentHashMap()
    private var scheduler: Scheduler = Scheduler(callFactory, interceptors)

    fun addInterceptor(interceptor: AuiuInterceptor) {
        interceptors.add(interceptor)
    }

    fun <T> create(service: Class<T>): T {
        return Proxy.newProxyInstance(
            service.classLoader,
            arrayOf<Class<*>>(service)
        ) { proxy, method, args ->
            var methodParser = methodService.get(method)
            if (methodParser == null) {
                methodParser = MethodParser.parse(baseUrl, method)
                methodService.put(method, methodParser)
            }

            val request = methodParser.newRequest(method, args)
            scheduler.newCall(request)
        } as T
    }

}